class CommentsController < ApplicationController
  before_filter :authenticate_user!
  # GET /comments
  # GET /comments.json
  def index
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @comments = Comment.all

      respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @comments }
      end
    end
  end

  # GET /comments/1
  # GET /comments/1.json
  def show
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @comment = Comment.find(params[:id])

      respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @comment }
      end
    end
  end

  # GET /comments/new
  # GET /comments/new.json
  def new
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @comment = Comment.new

      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @comment }
      end
    end
  end

  # GET /comments/1/edit
  def edit
    if session[:user].id != Comment.find(params[:id]).user_id
      redirect_to homepage_url
    else
      @comment = Comment.find(params[:id])
    end
  end

  # POST /comments
  # POST /comments.json
  def create
    @comment = Comment.new()
    @comment.book_id = params[:book][:book_id]
    @comment.user_id = session[:user].id
    @comment.content = params[:book][:comment]
    @comment.time_cm = Time.now
    respond_to do |format|
      if @comment.save
        format.html { redirect_to Book.find(params[:book][:book_id]) }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /comments/1
  # PUT /comments/1.json
  def update
    if session[:user].id != Comment.find(params[:id]).user_id
      redirect_to homepage_url
    else
      @comment = Comment.find(params[:id])

      respond_to do |format|
        if @comment.update_attributes(params[:comment])
          format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
          format.json { head :no_content }
        else
          format.html { render action: "edit" }
          format.json { render json: @comment.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @comment = Comment.find(params[:id])
      @comment.destroy

      respond_to do |format|
        format.html { redirect_to comments_url }
        format.json { head :no_content }
      end
    end
  end
end
